package frame;

import classes.*;

import javax.swing.*;
import java.awt.*;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

public class Home extends JFrame {

    private CardLayout cardLayout = new CardLayout();
    private JPanel body = new JPanel(cardLayout);

    public Home() {
        setTitle("简易图书管理");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setLayout(new BorderLayout());

        // body添加组件
        body.add(new FindBook(), "找书");
        body.add(new BorrowBook(), "借阅");
        body.add(new BorrowRecord(), "借阅记录");

        // 添加组件
        add(new Menu(), BorderLayout.NORTH);
        add(body, BorderLayout.CENTER);

        setVisible(true);
    }

    private class Menu extends JPanel {
        public Menu() {
            Box hBox = Box.createHorizontalBox();
            // 创建按钮
            JButton findBook = new JButton("找书");
            JButton borrowBook = new JButton("借阅");
            JButton borrowRecord = new JButton("借阅记录");
            // 添加事件
            findBook.addActionListener(e -> cardLayout.show(body, "找书"));
            borrowBook.addActionListener(e -> cardLayout.show(body, "借阅"));
            borrowRecord.addActionListener(e -> cardLayout.show(body, "借阅记录"));
            // 添加到布局
            hBox.add(findBook);
            hBox.add(borrowBook);
            hBox.add(borrowRecord);

            add(hBox, BorderLayout.NORTH);
        }
    }

    // 找书
    private class FindBook extends JPanel {
        private final JScrollPane scrollPane = new JScrollPane();

        public FindBook() {
            setBackground(Color.BLUE);
            setLayout(new BorderLayout());

            JPanel panel = new JPanel();
            panel.setLayout(new GridLayout(6, 2));

            JCheckBox titleBox = new JCheckBox("书名", true);
            JTextField titleField = new JTextField();
            titleBox.addItemListener(e -> titleField.setEditable(titleBox.isSelected()));
            panel.add(titleBox);
            panel.add(titleField);

            JCheckBox isbnBox = new JCheckBox("ISBN");
            JTextField isbnField = new JTextField();
            isbnField.setEditable(false);
            isbnBox.addItemListener(e -> isbnField.setEditable(isbnBox.isSelected()));
            panel.add(isbnBox);
            panel.add(isbnField);

            JCheckBox authorsBox = new JCheckBox("作者");
            JTextField authorsField = new JTextField();
            authorsField.setEditable(false);
            authorsBox.addItemListener(e -> authorsField.setEditable(authorsBox.isSelected()));
            panel.add(authorsBox);
            panel.add(authorsField);

            JCheckBox publisherBox = new JCheckBox("出版社");
            JTextField publisherField = new JTextField();
            publisherField.setEditable(false);
            publisherBox.addItemListener(e -> publisherField.setEditable(publisherBox.isSelected()));
            panel.add(publisherBox);
            panel.add(publisherField);

            JCheckBox publicationDateBox = new JCheckBox("出版日期");
            JTextField publicationDateField = new JTextField();
            publicationDateField.setEditable(false);
            publicationDateBox.addItemListener(e -> publicationDateField.setEditable(publicationDateBox.isSelected()));
            panel.add(publicationDateBox);
            panel.add(publicationDateField);

            JCheckBox typeBox = new JCheckBox("读物类型");
            JTextField typeField = new JTextField();
            typeField.setEditable(false);
            typeBox.addItemListener(e -> typeField.setEditable(typeBox.isSelected()));
            panel.add(typeBox);
            panel.add(typeField);

            JButton searchButton = new JButton("搜索");
            searchButton.addActionListener(e -> {
                StringBuilder sql = new StringBuilder("SELECT * FROM books WHERE ");
                if (titleBox.isSelected() && !titleField.getText().equals("")) {
                    sql.append("title LIKE '%").append(titleField.getText()).append("%' AND ");
                }
                if (isbnBox.isSelected() && !isbnField.getText().equals("")) {
                    sql.append("isbn LIKE '%").append(isbnField.getText()).append("%' AND ");
                }
                if (authorsBox.isSelected() && !authorsField.getText().equals("")) {
                    sql.append("authors LIKE '%").append(authorsField.getText()).append("%' AND ");
                }
                if (publisherBox.isSelected() && !publisherField.getText().equals("")) {
                    sql.append("publisher LIKE '%").append(publisherField.getText()).append("%' AND ");
                }
                if (publicationDateBox.isSelected() && !publicationDateField.getText().equals("")) {
                    sql.append("publicationDate LIKE '%").append(publicationDateField.getText()).append("%' AND ");
                }
                if (typeBox.isSelected() && !typeField.getText().equals("")) {
                    sql.append("type LIKE '%").append(typeField.getText()).append("%' AND ");
                }
                if (sql.toString().endsWith("AND ")) {
                    sql.delete(sql.length() - 5, sql.length());
                }
                String sqlStr = sql.toString();
                if (!sqlStr.equals("SELECT * FROM books WHERE "))
                    scrollPane.setViewportView(new SelectTable(sqlStr));
            });

            add(panel, BorderLayout.NORTH);
            add(scrollPane, BorderLayout.CENTER);
            add(searchButton, BorderLayout.SOUTH);
        }
    }

    // 借书
    private class BorrowBook extends JPanel {
        private JTextField readerID = new JTextField();
        private JTextField isbn = new JTextField();
        private final SpinnerNumberModel model = new SpinnerNumberModel(7, 1, 30, 1);
        private JSpinner dateSpinner = new JSpinner(model);

        public BorrowBook() {
            setBackground(Color.RED);
            setLayout(new BorderLayout());

            // 标签
            JLabel readerLabel = new JLabel("借阅人ID", JLabel.RIGHT);
            JLabel isbnLabel = new JLabel("借阅书ISBN", JLabel.RIGHT);
            JLabel borrowDateLabel = new JLabel("借书时间", JLabel.RIGHT);
            // 输入框
            dateSpinner.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
            // 按钮
            JButton borrowButton = new JButton("借书");
            borrowButton.addActionListener
                    (e -> borrowBook(readerID.getText(), isbn.getText(), (int) dateSpinner.getValue()));
            JButton returnButton = new JButton("还书");
            returnButton.addActionListener(e -> returnBook(readerID.getText(), isbn.getText()));

            JPanel body = new JPanel();
            body.setLayout(new GridLayout(11, 4));
            for (int i = 0; i < 44; i++) {
                if (i == 13) body.add(readerLabel);
                else if (i == 14) body.add(readerID);
                else if (i == 17) body.add(isbnLabel);
                else if (i == 18) body.add(isbn);
                else if (i == 21) body.add(borrowDateLabel);
                else if (i == 22) body.add(dateSpinner);
                else if (i == 29) body.add(borrowButton);
                else if (i == 30) body.add(returnButton);
                else
//                    body.add(new JButton(String.valueOf(i)));
                    body.add(new JLabel());
            }
            add(body);
        }

        private void borrowBook(String ReaderID, String isbn, int borrowTime) {
            if (ReaderID.equals("") || isbn.equals("")) {
                JOptionPane.showMessageDialog(null,
                        "请输入借阅人ID和借阅书ISBN", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            if (borrowTime < 1 || borrowTime > 30) {
                JOptionPane.showMessageDialog(null,
                        "借书时间不能小于1天，不能大于30天", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            Book book = MySQLConnector.getBook(isbn);
            if (book == null) {
                JOptionPane.showMessageDialog(null,
                        "没有这本书", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            Reader reader = MySQLConnector.getReader(Integer.parseInt(ReaderID));
            if (reader == null) {
                JOptionPane.showMessageDialog(null,
                        "没有这个读者", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            ArrayList<Record> records = MySQLConnector.getRecordByReaderID(ReaderID);
            if (records.size() >= reader.Limits) {
                JOptionPane.showMessageDialog(null,
                        "读者借书数量已达上限", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            ArrayList<Record> bookRecords = MySQLConnector.getRecordByISBN(isbn);
            if (bookRecords.size() > 0) {
                JOptionPane.showMessageDialog(null,
                        "这本书已经被借出", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            long timeMillis = System.currentTimeMillis();
            Date now = new Date(timeMillis);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(now);
            calendar.add(Calendar.DATE, borrowTime);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String insertRecord = "INSERT INTO record VALUES(%d, '%s', %d, '%s', '%s')";
            insertRecord = String.format(insertRecord, System.currentTimeMillis(), isbn, Integer.parseInt(ReaderID),
                    dateFormat.format(now), dateFormat.format(calendar.getTime()));
            MySQLConnector.update(insertRecord);
            JOptionPane.showMessageDialog(null, "借书成功",
                    "成功", JOptionPane.INFORMATION_MESSAGE);
        }

        private void returnBook(String ReaderID, String isbn) {
            String sql = "SELECT * FROM Record WHERE ReaderID = " + ReaderID + " AND ISBN = '" + isbn + "'";
            if (ReaderID.isEmpty() || isbn.isEmpty())
                JOptionPane.showMessageDialog(null,
                        "请输入借阅人ID和借阅书ISBN", "错误", JOptionPane.ERROR_MESSAGE);
            else if (MySQLConnector.getRecords(sql).isEmpty())
                JOptionPane.showMessageDialog(null,
                        "这个读者没有借这本书", "错误", JOptionPane.ERROR_MESSAGE);
            else {
                String deleteRecord = "DELETE FROM Record WHERE ReaderID = " + ReaderID + " AND ISBN = '" + isbn + "'";
                try{
                    MySQLConnector.update(deleteRecord);
                    JOptionPane.showMessageDialog(null, "还书成功",
                            "成功", JOptionPane.INFORMATION_MESSAGE);
                }catch (Exception e){
                    e.printStackTrace();
                    JOptionPane.showMessageDialog(null, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    }

    // 借阅记录
    private class BorrowRecord extends JPanel {
        private final JScrollPane scrollPane = new JScrollPane();

        public BorrowRecord() {
//            setBackground(Color.YELLOW);
            setLayout(new BorderLayout());

            // 读者ID输入框
            JLabel readerIDLabel = new JLabel("读者ID");
            JTextField readerID = new JTextField();
            JButton button = new JButton("查询");
            button.addActionListener(e -> search(readerID.getText()));
            Box readerIDBox = Box.createHorizontalBox();
            readerIDBox.add(readerIDLabel);
            readerIDBox.add(readerID);
            readerIDBox.add(button);
            add(readerIDBox, BorderLayout.NORTH);

            // 借阅记录
            add(scrollPane, BorderLayout.CENTER);
        }

        private void search(String readerID) {
            if (readerID.equals(""))
                scrollPane.setViewportView(new SelectTable("SELECT * FROM Record"));
            else
                scrollPane.setViewportView(new SelectTable("SELECT * FROM Record WHERE ReaderID = " + readerID));
        }
    }
}
